package com.quanyan.club.mq.consumer;

import com.alibaba.fastjson.JSON;
import com.alibaba.rocketmq.client.consumer.listener.ConsumeConcurrentlyContext;
import com.alibaba.rocketmq.common.message.MessageExt;
import com.quanyan.api.APIResponse;
import com.quanyan.club.entity.db.TbOrderRefund;
import com.quanyan.club.mq.constant.MqConstant;
import com.quanyan.club.service.ClubActivityService;
import com.quanyan.club.service.ClubRefundService;
import com.quanyan.common.constants.Constants;
import com.quanyan.common.utils.ObjectUtil;
import com.quanyan.mq.enums.MqConsumerStatus;
import com.quanyan.mq.mq.consumer.AbstractMqConsumer;
import com.quanyan.mq.mq.consumer.MqTopic;
import com.quanyan.orderpay.response.mq.RefundNotifyMsg;
import com.quanyan.orderpay.service.OrderPayService;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * @Author Hugo.Wwg
 * @Since 2016-06-25
 *
 * 订阅各种活动退款业务的consumer
 */
@Component
public class ActivityRefundConsumer extends AbstractMqConsumer {

    private static final Logger log = LoggerFactory.getLogger(ActivityRefundConsumer.class);

    @Autowired
    private ClubActivityService clubActivityService;
    @Autowired
    private ClubRefundService clubRefundService;

    @Value("${mq.nameServer.address}")
    private String nameServerAddress;

    @Override
    protected MqConsumerStatus process(List<MessageExt> messages, ConsumeConcurrentlyContext context) {
        MessageExt messageExt = messages.get(0);
        String msgId = messageExt.getKeys(); //退款单号
        byte[] bodyByte = messageExt.getBody();

        try {
            RefundNotifyMsg refundNotifyMsg = (RefundNotifyMsg) ObjectUtil.toObject(bodyByte);
            log.warn("---------退款回调返回：" + JSON.toJSONString(refundNotifyMsg));
            TbOrderRefund tbOrderRefund =
                    clubRefundService.queryOneTbOrderRefundRecord(refundNotifyMsg.getUid(), msgId);
            log.warn("----------tbOrderRefund=" + JSON.toJSONString(tbOrderRefund));
            if (tbOrderRefund == null) {
                //退款订单不存在,记录msgId 到 db 中
            }
            String businessOrderNo = refundNotifyMsg.getOutTradeNo();
            switch (tbOrderRefund.getRefundType().intValue()) {
                //1: 活动结算AA退款 2:用户取消已支付订单退款 3:管理员取消已支付订单退款 4:活动未达到开启条件,给已经报名支付成功的人退款 5现场管理人补请假退款
                case 1:
                    APIResponse apiResponse = clubActivityService.
                            handleActivitySettlementAARefundCallback(refundNotifyMsg, tbOrderRefund);
                    if (!apiResponse.isRet()) {
                        //todo 消费异常,记录msgId 到 db 中
                    }
                    break;

                case 2:
                    boolean isCanceled =
                            clubActivityService.cancelOrderNotifyCallback(businessOrderNo);
                    if (!isCanceled) {
                        log.error("处理俱乐部订单取消退款失败，MQ messageId={}", msgId);
                        //todo 消费异常,记录msgId 到 db 中
                    }
                    break;

                case 3:
                    boolean result = clubActivityService.
                            cancelActivityOrderAdminCallback(refundNotifyMsg);
                    if (!result) {
                        log.error("处理俱乐部活动订单取消退款失败，MQ messageId={}", msgId);
                        //todo 消费异常,记录msgId 到 db 中
                    }
                    break;

                case 4:
                    boolean cancel =
                            clubActivityService.cancelOrderNotifyCallback(businessOrderNo);
                    if (!cancel) {
                        log.error("处理  活动未达到开启条件(报名人数未满), 给已经报名支付成功的人退款失败，MQ messageId={}", msgId);
                        //todo 消费异常,记录msgId 到 db 中
                    }
                    break;

                case 5:
                    APIResponse supplementLeaveRes = clubActivityService
                            .supplementLeaveRefundOrderCallBack(refundNotifyMsg);
                    if (!supplementLeaveRes.isRet()) {
                        //todo 消费异常,记录msgId 到 db 中
                    }
                    break;

                default:
                    break;
            }


        } catch (Exception e) {
            //todo 消费异常,记录msgId 到 db 中
            log.error("消费异常，msgId【{}】，topic【{}】,tag【{}】,errorMsg【{}】", msgId,
                    OrderPayService.TOPIC_ORDER_STATUS_NOTIFY,
                    Constants.CLUB_SYSTEM_CODE, e.getMessage());
        }

        log.info(Thread.currentThread().getName() + " receive messages: " + messages.toString());

        return MqConsumerStatus.CONSUMER_SUCCESS;
    }

//    @PostConstruct
//    void run() {
//        super.start();
//    }

    @Override
    protected String getConsumerGroup() {
        return MqConstant.CLUB_ACTIVITY_ORDER_AA_REFUND_CALLBACK_GROUP;
    }

    @Override
    protected String getNameServerAddress() {
        return this.nameServerAddress;
    }

    @Override
    protected String getInstanceName() {
        return MqConstant.CLUB_ACTIVITY_ORDER_AA_REFUND_CALLBACK_INSTANCE_NAME;
    }

    @Override
    protected MqTopic[] getMqTopics() {
        MqTopic[] mqTopics = new MqTopic[1];
        mqTopics[0] = new MqTopic(
                OrderPayService.TOPIC_ORDER_REFUND_STATUS_NOTIFY, Constants.CLUB_SYSTEM_CODE);
        return mqTopics;
    }
}
